package org.syyo.admin.utils;

import org.hibernate.validator.HibernateValidator;
import org.syyo.admin.common.enums.ResultEnum;
import org.syyo.admin.common.exception.SysException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @Auther: wangzhong
 * @Date: 2019/7/3 10:20
 * @Description: 参数校验框架
 */
public class CheckUtils {

    /**
     * 使用hibernate的注解来进行验证
     */
    private static Validator validator = Validation
            .byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();

    /**
     * 功能描述: <br>
     * 〈注解验证参数〉
     *
     * @param obj
     */
    public static <T> void validate(T obj) {
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
        // 抛出检验异常

        if (constraintViolations.size() > 0) {
            SysException e = new SysException(ResultEnum.NOT_NULL.getCode(), String.format(constraintViolations.iterator().next().getMessage()));
//            Path propertyPath = constraintViolations.iterator().next().getPropertyPath();// 字段校验未通过的字段名称
//            e.setPath(propertyPath);
            throw e;
        }
    }
}
